package com.sihai.ehr.web.action.exam;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.AuditType;
import com.sihai.ehr.model.biz.Duty;
import com.sihai.ehr.model.biz.EmployeeWorkExperience;
import com.sihai.ehr.model.biz.EmployeeinfoEducation;
import com.sihai.ehr.model.biz.EmployeeinfoFamily;
import com.sihai.ehr.model.biz.EmployeeinfoTrain;
import com.sihai.ehr.model.biz.ExamAward;
import com.sihai.ehr.model.biz.ExamAwardAuditing;
import com.sihai.ehr.model.biz.ExamAwardItem;
import com.sihai.ehr.model.biz.TrainPlanAuditing;
import com.sihai.ehr.model.sys.AuditStatus;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.service.EmployeeService;
import com.sihai.ehr.service.ExamAwardService;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.web.action.EHRAction;

/**
 * 考核奖惩控制器
 * 
 * @author henry
 * 
 */
@Results({
		@Result(name = "award_list", location = "exam_award_list.jsp"),
		@Result(name = "award_audit_list", location = "exam_award_audit_list.jsp"),
		@Result(name = "award_audit_detail", location = "exam_award_audit_detail.jsp"),
		@Result(name = "award_manage", location = "exam_award_manage.jsp"),
		@Result(name = "main", location = "exam_award_main.jsp"),
		@Result(name = "staff_award_list", location = "/WEB-INF/pages/exam/exam_staff_award_list.jsp") })
public class ExamAwardAction extends EHRAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	Log log = LogFactory.getLog(ExamAwardAction.class);

	private List<Organization> organizations;
	@BeanInject
	private OrganizationService organizationService;
	@BeanInject
	private EmployeeService employeeService;
	@BeanInject
	private ExamAwardService examAwardService;

	private LimitedList<ExamAward> awards;
	private List<EmployeeinfoFamily> families;
	private List<EmployeeinfoEducation> educations;
	private List<EmployeeinfoTrain> trains;
	private List<EmployeeWorkExperience> experiences;
	private List<List<ExamAwardAuditing>> audits;
	private ExamAward examAward;

	private Long awardId;

	private String ids;
	private Long workId;
	private String module;
	private int startYear;
	private int endYear;
	private int year;
	private int month;

	@Action("/exam/award_browse_main")
	@Override
	public String execute() throws Exception {
		listAction = "/exam/award_list.xhtml";
		listTitle = "奖惩浏览";
		organizations = organizationService
				.findChildren(null, true, null, null);
		if (organizations != null && organizations.size() > 0) {
			if (getCurrentUserId() > 0) {
				Long topOrgId = getCurrentUser().getWork().getOrganization()
						.getTopOrganization().getId();
				Iterator<Organization> it = organizations.iterator();
				while (it.hasNext()) {
					Organization o = it.next();
					if (o.getId() != topOrgId) {
						it.remove();
					}
				}
			}
			organizationId = organizations.get(0).getId();
		}
		showChildOrg = false;
		module = "examaward";

		try {
			startYear = NumberUtils.createInteger(PropertiesLoaderUtils
					.loadAllProperties("jdbc.properties").getProperty(
							"attendance_start_year", "2001"));
		} catch (Exception e) {
			startYear = 2001;
		}
		setCurrentYearAndMonth();

		return "main";
	}

	// award_audit_main
	@Action("/exam/award_audit_main")
	public String awardBrowse() throws Exception {
		listAction = "/exam/award_audit_list.xhtml";
		listTitle = "员工奖惩审核";
		organizations = organizationService
				.findChildren(null, true, null, null);
		if (organizations != null && organizations.size() > 0) {
			if (getCurrentUserId() > 0) {
				Long topOrgId = getCurrentUser().getWork().getOrganization()
						.getTopOrganization().getId();
				Iterator<Organization> it = organizations.iterator();
				while (it.hasNext()) {
					Organization o = it.next();
					if (o.getId() != topOrgId) {
						it.remove();
					}
				}
			}
			organizationId = organizations.get(0).getId();
		}
		showChildOrg = false;
		module = "examaward";
		try {
			startYear = NumberUtils.createInteger(PropertiesLoaderUtils
					.loadAllProperties("jdbc.properties").getProperty(
							"attendance_start_year", "2001"));
		} catch (Exception e) {
			startYear = 2001;
		}
		setCurrentYearAndMonth();

		return "main";
	}

	private void setCurrentYearAndMonth() {
		endYear = Calendar.getInstance().get(Calendar.YEAR);
		year = endYear;
		month = Calendar.getInstance().get(Calendar.MONTH);
		if (month == 0) {
			month = 12;
			year = year - 1;
		}
	}

	/**
	 * 获取奖励对象列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/exam/award_list")
	public String awardList() throws Exception {
		awards = examAwardService.searchExamAward(organizationId, -1,year,month,
				createLimit(), createSorter());
		this.paging(awards);
		setPageUrl("exam/award_list.xhtml");
		return "award_list";
	}

	@Action("/public/staff_award_list")
	public String queryStaffAwardList() throws Exception {
		awards = examAwardService.searchExamAwardByWorkId(workId,
				createLimit(), createSorter());
		this.paging(awards);
		setPageUrl("public/staff_award_list.xhtml");
		return "staff_award_list";
	}

	/**
	 * 获取奖励对象列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/exam/award_audit_list")
	public String awardAuditList() throws Exception {
		awards = examAwardService.searchExamAward(organizationId, -1,year,month,
				createLimit(), createSorter());
		this.paging(awards);
		setPageUrl("exam/award_audit_list.xhtml");
		return "award_audit_list";
	}

	/**
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/exam/award_audit_detail")
	public String awardAuditDetail() throws Exception {
		// -----
		if (awardId == null && awardId < 0) {
			if (log.isErrorEnabled()) {
				log.equals("【awardId对象为空】");
			}
			return ERROR;
		}
		examAward = examAwardService.getExamAward(awardId);

		families = employeeService.getEmployeeFamilyList(examAward
				.getEmployeeinfoWork().getBaseId(), null, null);

		educations = employeeService.getEducationList(examAward
				.getEmployeeinfoWork().getBaseId(), null, null);

		trains = employeeService.getTrainList(examAward.getEmployeeinfoWork()
				.getBaseId(), null, null);

		experiences = employeeService.getWorkExperienceList(examAward
				.getEmployeeinfoWork().getBaseId(), null, null);

		audits = examAwardService.searchExamAwardAuditings(awardId, null, null);
		if (audits == null || audits.isEmpty()) {
			examAwardService.saveAwardAuditingProcess(examAward, 1);
			audits = examAwardService.searchExamAwardAuditings(
					examAward.getId(), null, null);
		}
		// 检查当前登录用户是否可以审核当前结点
		if (audits != null && !audits.isEmpty()) {
			checkCanAudit((Duty) null, audits.get(audits.size() - 1));
		}
		currentAuditType = AuditType.audit_exam_award.toString();
		return "award_audit_detail";
	}

	@Action("/exam/award_manage")
	public String dispatchAwardManage() throws Exception {
		if (awardId != null && awardId > 0) {
			// 修改
			examAward = examAwardService.getExamAward(awardId);
		} else {
			examAward = new ExamAward();
		}
		return "award_manage";
	}

	@Action("/exam/post_award")
	public String postAward() throws Exception {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		if (examAward == null) {
			if (log.isErrorEnabled()) {
				log.equals("【奖惩对象为空】");
			}
			return ERROR;
		}
		if (examAward.getAwardType() < 0) {
			if (log.isErrorEnabled()) {
				log.equals("【奖惩类型不能为空】");
			}
			return ERROR;
		}

		try {
			examAward.setAuditStatus(AuditStatus.wait_audit);
			examAward.setAwardDate(formatter.parse(getParameter("award_date")));
			examAwardService.saveExamAward(examAward);
		} catch (Exception e) {
			// TODO: handle exception
		}

		return "main";
	}

	@Action(value = "/exam/award_delete", results = { @Result(name = "success", type = "plainText") })
	public String deleteAwardItem() throws Exception {
		if (StringUtils.isNotBlank(ids)) {
			try {
				examAwardService.removeExamAward(ids);
			} catch (Exception e) {
				if (log.isErrorEnabled()) {
					log.error(e.getMessage());
				}
				return ERROR;
			}
		}

		return SUCCESS;
	}

	public void setOrganizations(List<Organization> organizations) {
		this.organizations = organizations;
	}

	public List<Organization> getOrganizations() {
		return organizations;
	}

	public void setAwards(LimitedList<ExamAward> awards) {
		this.awards = awards;
	}

	public LimitedList<ExamAward> getAwards() {
		return awards;
	}

	public void setFamilies(List<EmployeeinfoFamily> families) {
		this.families = families;
	}

	public List<EmployeeinfoFamily> getFamilies() {
		return families;
	}

	public void setEducations(List<EmployeeinfoEducation> educations) {
		this.educations = educations;
	}

	public List<EmployeeinfoEducation> getEducations() {
		return educations;
	}

	public List<EmployeeinfoTrain> getTrains() {
		return trains;
	}

	public void setTrains(List<EmployeeinfoTrain> trains) {
		this.trains = trains;
	}

	public void setExperiences(List<EmployeeWorkExperience> experiences) {
		this.experiences = experiences;
	}

	public List<EmployeeWorkExperience> getExperiences() {
		return experiences;
	}

	public void setAudits(List<List<ExamAwardAuditing>> audits) {
		this.audits = audits;
	}

	public List<List<ExamAwardAuditing>> getAudits() {
		return audits;
	}

	public void setExamAward(ExamAward examAward) {
		this.examAward = examAward;
	}

	public ExamAward getExamAward() {
		return examAward;
	}

	public void setAwardId(Long awardId) {
		this.awardId = awardId;
	}

	public Long getAwardId() {
		return awardId;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getIds() {
		return ids;
	}

	public Long getWorkId() {
		return workId;
	}

	public void setWorkId(Long workId) {
		this.workId = workId;
	}

	public String getModule() {
		return module;
	}
	
    public int getStartYear() {
        return startYear;
    }

    public int getEndYear() {
        return endYear;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }
}
